<?php
/**
 * FileName: LogService.php
 * Author: Fei.Song
 * Date: 2021/4/8 18:16
 * Created by PhpStorm
 * Desc:
 */

namespace App\Service;

use App\Lib\Logger;
use App\Models\Log;

class LogService extends BaseService {
    /**
     * @param $level
     * @param $module
     * @param $action
     * @param $message
     * @param $data
     */
    public function log($level, $module, $action, $message, $data = null) {
        $this->addLog($level, $module, $action, $message, $data);
    }

    protected function addLog($level, $module, $action, $message, $data = null) {
        $level='App\Lib\Logger::'.'LOG_LEVEL_'.strtoupper($level);
        $level=constant($level);
        $temp["id"]=0;
        $temp["login_ip"]=0;
        $user=empty(getCurrentUser())?$temp:getCurrentUser();
        $log=[
            'level'=>$level,
            'module'=>$module,
            'action'=>$action,
            'message'=>$message,
            'data'=>is_array($data)?json_encode($data):$data,
            'user_id'=>$user['id'],
            'site_id'=>getCurrentSiteId(),
            'ip'=>$user['login_ip']
        ];
        (new Log())->create($log);
    }

    public function getLogList($limit,$search) {
        $site_id = getCurrentSiteId();
        $res = Log::withoutGlobalScope('site_id_scope')
            ->leftJoin('admin_user as a','log.user_id','a.id')
            ->select('log.*','a.real_name')
            ->where(function($query) use ($search){
                if(!empty($search['real_name'])){
                    $query->where("real_name","like","%".$search['real_name']."%");
                }
                if(!empty($search['date'])){
                    $date = explode("~",$search['date']);
                    $query->whereBetween("log.created_at",[strtotime($date[0]),strtotime($date[1])+86399]);
                }
                if(!empty($search['level'])){
                    $query->where("level",$search['level']);
                }
                if(!empty($search['module'])){
                    $query->where("module",$search['module']);
                }
                if(!empty($search['config'])){
                    $query->where("action",$search['config']);
                }
            })
            ->where("log.site_id",$site_id)->orderBy('id','desc')->paginate($limit)->toArray();
        $arr = Logger::getLogLevel();

        foreach ($res['data'] as $k=>$v){
            $res['data'][$k]['created_at'] = date("Y-m-d H:i:s",strtotime($v['created_at']));;
            $res['data'][$k]['level'] = $arr[$v['level']];
            $res['data'][$k]['data'] = json_encode($v['data']);
        }
        return $res;
    }
}
